<template>
	<a-card :bordered="false" class="mb-3">
		<div class="flex justify-between items-start">
			<a-form
				ref="searchFormRef"
				name="advanced_search"
				:model="searchFormState"
				class="ant-advanced-search-form"
				style="width: calc(100% - 100px)"
			>
				<a-space :size="16" class="flex-wrap">
					<a-form-item label="人员范围" name="data" class="mb-0">
						<a-select
							v-model:value="searchFormState.data"
							style="width: 180px"
							placeholder="请选择"
							@change="onDepartmentChange"
						>
							<a-select-option v-if="store.roleAuthMap.self" value="1">本人</a-select-option>
							<a-select-option v-if="store.roleAuthMap.dept" value="2">本部门</a-select-option>
							<a-select-option v-if="store.roleAuthMap.deptAndSub" value="3">本部门及下级部门</a-select-option>
							<a-select-option v-if="store.roleAuthMap.all" value="4">全企业</a-select-option>
							<a-select-option v-if="store.roleAuthMap.dept" value="5" @click="onCustomClick">自定义</a-select-option>
						</a-select>
					</a-form-item>
					<a-form-item v-if="searchFormState.data === '5'" name="tempPersonIds" class="mb-0">
						<a-tree-select
							v-model:value="searchFormState.tempPersonIds"
							style="width: 360px"
							:tree-data="orgUserTreeData"
							tree-checkable
							allow-clear
							:show-checked-strategy="SHOW_PARENT"
							placeholder="请选择人员范围"
							tree-node-filter-prop="label"
							:fieldNames="fieldNames"
							max-tag-count="responsive"
							:dropdownMatchSelectWidth="false"
							treeNodeFilterProp="name"
							@change="onPersonChange"
						/>
					</a-form-item>
					<a-form-item label="时间" name="timeRange" class="mb-0">
						<a-range-picker
							v-model:value="searchFormState.timeRange"
							:disabled-date="disabledDate"
							allowClear
							style="width: 100%"
							@calendarChange="onCalendarChange"
						/>
					</a-form-item>
					<a-form-item label="通信方式" name="communicationType" class="mb-0">
						<a-select
							v-model:value="searchFormState.communicationType"
							placeholder="请选择"
							:options="[{ label: '全部', value: '' }, ...communicationTypeOptions]"
							style="width: 196px"
							@change="onCommunicationTypeChange"
						></a-select>
					</a-form-item>
					<a-form-item label="通信对象" name="souceType" class="mb-0">
						<a-select
							v-model:value="searchFormState.souceType"
							placeholder="请选择"
							:options="[{ label: '全部', value: '' }, ...communicationObjectOptions]"
							style="width: 196px"
							@change="onCommunicationObjectChange"
						></a-select>
					</a-form-item>
					<a-button @click="reset">重置</a-button>
				</a-space>
			</a-form>
		</div>
	</a-card>
	<a-spin :spinning="onLoading" size="large" style="min-height: 70vh">
		<a-card :loading="onLoading" :bordered="false" class="mb-3">
			<div class="flex flex-wrap">
				<div
					v-for="(item, index) in fieldList"
					:key="index"
					class="mx-4 my-3 p-2 w-[250px] flex flex-col justify-center border-[1px] border-solid border-zinc-300 rounded-md cursor-pointer"
				>
					<div class="ml-4 my-2 text-[16px] flex justify-between items-center">
						<span>{{ item.title }}</span>
						<a-tooltip>
							<template #title>{{ item.tip }}</template>
							<question-circle-outlined
								class="mr-3"
								:style="{
									color: '#bbb'
								}"
							/>
						</a-tooltip>
					</div>
					<div class="ml-4 mb-4 text-[17px]">{{ statisticsData[item.field] || item.defaultVal }}</div>
				</div>
			</div>
		</a-card>
		<a-card :loading="onLoading" :bordered="false" class="mb-3">
			<div class="section-title">明细数据</div>
			<div class="flex justify-between">
				<div class="leading-[32px]">发生通话人员</div>
				<a-button type="primary" @click="onExport">
					<template #icon><export-outlined /></template>
					导出
				</a-button>
			</div>
			<s-table
				ref="table"
				:columns="columns"
				:data="loadData"
				:alert="false"
				bordered
				:row-key="(record) => record.id"
				:tool-config="toolConfig"
			>
				<template #headerCell="{ column }">
					<template v-for="(item, index) in fieldList">
						<template v-if="column.dataIndex === item.field">
							<span :key="index">
								<span>{{ item.title }}</span>
								<a-tooltip>
									<template #title>{{ item.tip }}</template>
									<question-circle-outlined
										class="ml-1"
										:style="{
											color: '#bbb'
										}"
									/>
								</a-tooltip>
							</span>
						</template>
					</template>

					<template v-if="column.dataIndex === 'validTotalDuration'">
						<span>
							<span>有效通话总时长</span>
							<a-tooltip>
								<template #title>选择条件范围内，达到系统设定的有效通话的总通话时长</template>
								<question-circle-outlined
									class="ml-1"
									:style="{
										color: '#bbb'
									}"
								/>
							</a-tooltip>
						</span>
					</template>
				</template>
			</s-table>

			<div class="flex justify-between">
				<div class="leading-[32px]">未发生通话人员</div>
			</div>
			<s-table
				ref="table"
				:columns="columns"
				:data="unFinishLoadData"
				:alert="false"
				bordered
				:row-key="(record) => record.id"
				:tool-config="toolConfig"
				:show-sorter-tooltip="false"
			>
				<template #headerCell="{ column }">
					<template v-for="(item, index) in fieldList">
						<template v-if="column.dataIndex === item.field">
							<span :key="index">
								<span>{{ item.title }}</span>
								<a-tooltip>
									<template #title>{{ item.tip }}</template>
									<question-circle-outlined
										class="ml-1"
										:style="{
											color: '#bbb'
										}"
									/>
								</a-tooltip>
							</span>
						</template>
					</template>

					<template v-if="column.dataIndex === 'validTotalDuration'">
						<span>
							<span>有效通话总时长</span>
							<a-tooltip>
								<template #title>选择条件范围内，达到系统设定的有效通话的总通话时长</template>
								<question-circle-outlined
									class="ml-1"
									:style="{
										color: '#bbb'
									}"
								/>
							</a-tooltip>
						</span>
					</template>
				</template>
			</s-table>
		</a-card>
	</a-spin>
</template>
<script setup>
	import { TreeSelect } from 'ant-design-vue'
	import callStatisticsApi from '@/api/biz/callStatisticsApi'
	import downloadUtil from '@/utils/downloadUtil'
	import dayjs from 'dayjs'
	import { globalStore } from '@/store'
	import {
		communicationTypeOptions,
		communicationObjectOptions
	} from '@/views/biz/contractManagement/enum/contractEnum'
	import tool from '@/utils/tool'

	const store = globalStore()

	const fieldList = [
		{ field: 'callNum', title: '呼出次数', tip: '选择条件范围内，呼出次数的总和，包括接听和未接听的', defaultVal: 0 },
		{ field: 'answerNum', title: '接听次数', tip: '选择条件范围内，呼出电话累计接听的次数', defaultVal: 0 },
		{ field: 'answerRate', title: '接听率', tip: '选择条件范围内，电话呼出的总接听率', defaultVal: '0.00%' },
		{
			field: 'personNum',
			title: '通话人数',
			tip: '选择条件范围内，去重后的呼叫人数，包括接听和未接听的',
			defaultVal: 0
		},
		{
			field: 'validThroughNum',
			title: '有效通话次数',
			tip: '选择条件范围内，达到系统设定的有效通话时长的总次数',
			defaultVal: 0
		},
		{
			field: 'callTotalDuration',
			title: '通话总时长',
			tip: '选择条件范围内，所有通话时长的总和为通话总时长',
			defaultVal: '00小时00分00秒'
		},
		{
			field: 'aveCallDuration',
			title: '平均通话时长',
			tip: '选择条件范围内，平均每次通话的时长',
			defaultVal: '00小时00分00秒'
		}
	]

	const onLoading = ref(true)

	onMounted(() => {
		getCallStatistics()
	})

	const getParams = () => {
		const { data, personIds, timeRange, communicationType, souceType } = searchFormState
		return {
			data,
			dataStr: personIds.join(','),
			stime: timeRange[0]?.format('YYYY-MM-DD'),
			etime: timeRange[1]?.format('YYYY-MM-DD'),
			communicationType,
			souceType
		}
	}

	const statisticsData = reactive({})
	const getCallStatistics = () => {
		onLoading.value = true
		const params = getParams()
		callStatisticsApi.getStatistics(params).then((data) => {
			Object.assign(statisticsData, data)
			onLoading.value = false
		})
	}

	let searchFormState = reactive({
		data: store.roleAuthMap.dept ? '2' : '1',
		tempPersonIds: [],
		personIds: [],
		timeRange: [dayjs(), dayjs()],
		communicationType: null,
		souceType: null
	})
	const searchFormRef = ref()

	const onDepartmentChange = (value) => {
		nextTick(() => {
			if (value !== '5') {
				onCustomClick()
				getCallStatistics()
			}
		})
	}

	const onCustomClick = () => {
		searchFormState.tempPersonIds = []
		searchFormState.personIds = []
	}

	const SHOW_PARENT = TreeSelect.SHOW_PARENT
	const fieldNames = {
		label: 'name',
		value: 'id'
	}
	const orgUserTreeData = ref(store.authDeptList)
	const onPersonChange = (value, label, extra) => {
		searchFormState.personIds = tool.getAllBottomPersonIds(extra.allCheckedNodes)
		getCallStatistics()
	}

	const dates = ref()
	const disabledDate = (current) => {
		if (!dates.value || dates.value.length === 0) {
			return false
		}
		const tooLate = dates.value[0] && current.diff(dates.value[0], 'days') > 90
		const tooEarly = dates.value[1] && dates.value[1].diff(current, 'days') > 90
		return tooEarly || tooLate
	}
	const onCalendarChange = (val) => {
		dates.value = val
		nextTick(() => {
			if (val.length === 2 && val[1]) {
				getCallStatistics()
			}
		})
	}

	// 通讯方式
	const onCommunicationTypeChange = (value) => {
		getCallStatistics()
	}

	// 通讯对象
	const onCommunicationObjectChange = (value) => {
		getCallStatistics()
	}

	// 重置
	const reset = () => {
		searchFormState.tempPersonIds = []
		searchFormState.personIds = []
		searchFormRef.value.resetFields()
		getCallStatistics()
	}

	// 导出
	const onExport = () => {
		const params = getParams()
		callStatisticsApi.exportList(params).then((res) => {
			downloadUtil.resultDownload(res)
		})
	}

	// 表格
	const table = ref()
	const toolConfig = { refresh: false, height: false, columnSetting: false, striped: false }
	const columns = [
		{
			title: '人员',
			dataIndex: 'customerName',
			ellipsis: true
		},
		{
			title: '通话人数',
			dataIndex: 'personNum',
			customRender: ({ text }) => text || 0,
			sorter: (a, b) => a.personNum - b.personNum
		},
		{
			title: '通话总时长',
			dataIndex: 'callTotalDuration',
			customRender: ({ text }) => text || '00小时00分00秒',
			sorter: (a, b) => a.callTotalDuration - b.callTotalDuration
		},
		{
			title: '呼出次数',
			dataIndex: 'callNum',
			customRender: ({ text }) => text || 0,
			sorter: (a, b) => a.callNum - b.callNum
		},
		{
			title: '接听次数',
			dataIndex: 'answerNum',
			customRender: ({ text }) => text || 0,
			sorter: (a, b) => a.answerNum - b.answerNum
		},
		{
			title: '接听率',
			dataIndex: 'answerRate',
			customRender: ({ text }) => text || '0%',
			sorter: (a, b) => a.answerRate - b.answerRate
		},
		{
			title: '有效通话次数',
			dataIndex: 'validThroughNum',
			customRender: ({ text }) => text || 0,
			sorter: (a, b) => a.validThroughNum - b.validThroughNum
		},
		{
			title: '有效通话总时长',
			dataIndex: 'validTotalDuration',
			customRender: ({ text }) => text || '00小时00分00秒',
			sorter: (a, b) => a.validTotalDuration - b.validTotalDuration
		}
	]
	const loadData = (parameter) => {
		const params = getParams()
		return callStatisticsApi.getList({ ...parameter, ...params }).then((data) => {
			return data
		})
	}
	const unFinishLoadData = (parameter) => {
		const params = getParams()
		return callStatisticsApi.getUnFinishList({ ...parameter, ...params }).then((data) => {
			return data
		})
	}
</script>

<style lang="less" scoped>
	.section-title {
		position: relative;
		margin: 0 0 12px 0;
		padding-left: 18px;
		font-size: 18px;
		font-weight: 600;
		line-height: 1;
		&::after {
			content: '';
			position: absolute;
			left: 0;
			top: 0;
			width: 5px;
			height: 100%;
			border-radius: 1px;
			background: var(--primary-7);
		}
	}
</style>
